<template>
    <div :id="'monitor'+props.options.onlyId" class="monitor">
        <div class="monitor-head">
            <div class="monitor-title">{{ state.isPlayBack ? props.options.name + '回放中...' : props.options.name }}</div>
            <div class="menu-list">
                <div v-if="state.isPlayBack" class="menu-btn" @click="state.isPlayBack = false">
                    <img
                        src="@/assets/monitor/fhjk.png"
                        alt="结束回放"
                    />
                </div>
                <div v-if="!state.isPlayBack" class="menu-btn" @click="changeHd">
                    <span v-if="state.isHd" title="切换到标清">高清</span>
                    <span v-else title="切换到高清">标清</span>
                </div>
                <div v-if="state.isLarge" class="menu-btn">
                    <img
                        src="@/assets/monitor/magin_small.png"
                        alt="缩小"
                        @click="maginMoniSmall"
                    />
                </div>
                <div v-else class="menu-btn" ref="maginBtn">
                    <img
                        src="@/assets/monitor/magin.png"
                        alt="放大"
                        @click="maginMoni"
                    />
                </div>
                <div v-if="!state.isLarge" class="menu-btn" @click="playback">
                    <img
                        src="@/assets/monitor/play_back.png"
                        alt="回放"
                    />
                </div>
                <div class="menu-btn" @click="closeVideo">
                    <img
                        src="@/assets/monitor/close_single.png"
                        alt="关闭"
                    />
                </div>
            </div>
        </div>
        <div class="iframe-box" :class="'container' + props.options.onlyId">
            <!-- 回放 -->
            <!-- 如果不加key，在全屏下切换回放为监控，会有问题 -->
            <div v-if="state.isPlayBack" :key="props.options.onlyId + 'key'" class="iframe">
                <div :id="'plackback' + props.options.onlyId"></div>
            </div>
            <!-- 监控 -->
            <iframe
                v-else
                :id="'iframe' + props.options.onlyId"
                :ref="el => iframeRef[props.options.onlyId] = el"
                class="iframe"
                :src="state.isHd ? state.hdUrl : state.ldUrl"
                allowfullscreen
                webkitallowfullscreen
                mozallowfullscreen
                frameborder="0"
                width="100%"
            ></iframe>
            <!-- 遮罩层阻止双击放大 -->
            <div class="mask-layer"></div>
            <div v-if="state.isLarge && !state.isPlayBack" class="top direction" @click="ptzControl(0)"></div>
            <div v-if="state.isLarge && !state.isPlayBack" class="left direction" @click="ptzControl(2)"></div>
            <div v-if="state.isLarge && !state.isPlayBack" class="right direction" @click="ptzControl(3)"></div>
            <div v-if="state.isLarge && !state.isPlayBack" class="bottom direction" @click="ptzControl(1)"></div>
        </div>
        <el-dialog
            title="监控回放"
            v-model="state.dialogVisible"
            width="600px"
            :close-on-click-modal="false"
            :before-close="handleClose"
        >
            <div class="dialog-play-back">
                <div class="time">
                    <span>选择日期时间段：</span>
                    <el-date-picker
                        v-model="state.dataValue"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYYMMDDHHmmss"
                        :picker-options="state.pickerOptions"
                    />
                </div>
            </div>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleConfirm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="jsx" setup>
import { reactive, ref, watch, onMounted, nextTick } from 'vue'
import { throttle } from 'lodash-es'
import EZUIKit from 'ezuikit-js'
import { useResizeObserver } from '@vueuse/core'

defineOptions({
    name: 'MonitorRealPlay'
})

const emit = defineEmits(['closeVideo'])

const props = defineProps({
    options: {
        type: Object,
        default: () => {}
    }
})

const state = reactive({
    isLarge: false,
    isHd: false,
    isPlayBack: false,
    ldUrl: '',
    hdUrl: '',
    dialogVisible: false,
    dataValue: null,
    pickerOptions: {
        disabledDate (time) {
            return time.getTime() > Date.now()
        }
    },
    playbackUrl: '',
    originalWidth: '',
    actWindow: {}

})

// 监听是否处于回放 不是清空日期选项
watch(
    () => state.isPlayBack,
    val => {
        if (!val) {
            state.dataValue = null
        }
    }
)

const iframeRef = ref({})

onMounted(async () => {
    await nextTick(() => {
        const element = document.querySelector(`.container${props.options.onlyId}`)
        useResizeObserver(element, resetElement)
    })
    getIfarmeUrl()
    keydownEsc()
})

const player = ref(null)

const changeHd = () => {
    state.isHd = !state.isHd
}

const maginBtn = ref(null)

const maginMoniSmall = () => {
    state.isLarge = false
    if (document.exitFullscreen) {
        document.exitFullscreen()
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
    }
}

const resetMoni = onlyId => {
    // 获取iframe 更新src属性
    iframeRef.value[onlyId].src = state.isHd ? state.hdUrl : state.ldUrl
}
const maginMoni = () => {
    state.isLarge = true
    if (state.isPlayBack) {
        // 回放监控全屏时，缩小大小会异常
        const el = document.querySelector(`.container${props.options.onlyId}`)
        state.originalWidth = el.offsetWidth
    }
    let elemet = document.getElementById('monitor' + props.options.onlyId)
    if (elemet.requestFullscreen) {
        elemet.requestFullscreen()
    } else if (elemet.webkitRequestFullScreen) {
        elemet.webkitRequestFullScreen()
    } else if (elemet.mozRequestFullScreen) {
        elemet.mozRequestFullScreen()
    } else {
        elemet.msRequestFullscreen()
    }
}

const resetElement = () => {
    if (state.isPlayBack) {
        const el = document.querySelector(`.container${props.options.onlyId}`)
        const height = el.offsetHeight - 48
        let width = el.offsetWidth
        if (state.originalWidth && !state.isLarge) {
            width = state.originalWidth
            state.originalWidth = ''
        }
        const wrap = document.querySelector(`#plackback${props.options.onlyId}-wrap`)
        wrap.style.width = width + 'px'
        const play = document.querySelector(`#plackback${props.options.onlyId}`)
        play.style.width = width + 'px'
        play.style.height = height + 'px'
        const parentWnd = document.querySelector(`.plackback${props.options.onlyId}parent-wnd`)
        parentWnd.style.width = width + 'px'
        parentWnd.style.height = height + 'px'
        parentWnd.firstChild.style.width = width + 'px'
        parentWnd.firstChild.style.height = height + 'px'
        const img = document.querySelector(`.plackback${props.options.onlyId}play-window`)
        img.style.width = width + 'px'
        img.style.height = height + 'px'
    }
}

const keydownEsc = () => {
    // 全屏模式下会屏蔽Esc按键的监听，不能使用键盘监听事件，跟双击退出全屏播放单个监控一样重置样式
    window.onresize = () => {
        const isFull
        = document.fullscreenElement
        || document.mozFullScreenElement
        || document.webkitFullscreenElement
        if (!isFull) {
            state.isLarge = false
        }
    }
}

const clearTime = () => {
    state.dataValue2 = null
}

// 回放
const playback = () => {
    state.dialogVisible = true
}

// 关闭视频
const closeVideo = () => {
    maginMoniSmall()
    emit('closeVideo', props.options.onlyId)
}

// 雲台
const ptzControl = throttle(async num => {
    const params = {
        channelNo: props.options.channelNo,
        deviceSerial: props.options.deviceSerial,
        direction: num
    }
    // await api.ptzCtrol(params)
})

// 获取播放地址
const getIfarmeUrl = () => {
    state.ldUrl = ''
    state.hdUrl = ''
    state.isPlayBack = false
    const baseUrl = 'https://open.ys7.com/ezopen/h5/iframe?url=ezopen://open.ys7.com/'
    state.ldUrl = baseUrl + props.options.deviceSerial + '/' + props.options.channelNo + '.live&autoplay=1&accessToken=' + props.options.accessToken + '&templete=0&audio=0' // audio: 0 关闭 1 开启
    state.hdUrl = baseUrl + props.options.deviceSerial + '/' + props.options.channelNo + '.hd.live&autoplay=1&accessToken=' + props.options.accessToken + '&templete=0&audio=0'
}

const handleClose = () => {
    state.dialogVisible = false
}

const handleConfirm = () => {
    if (state.dataValue) {
        state.dialogVisible = false
        if (state.player) {
            state.player.stop().then(() => {
                state.player = null
                state.isPlayBack = true
                nextTick(() => {
                    playbackMode()
                })
            })
        } else {
            state.isPlayBack = true
            nextTick(() => {
                playbackMode()
            })
        }
    } else {
        ElMessage.error('请先选择日期和时间段')
    }
}

const playbackMode = () => {
    const url = `ezopen://open.ys7.com/${props.options.deviceSerial}/${props.options.channelNo}.rec?begin=${state.dataValue[0]}&end=${state.dataValue[1]}`
    const element = document.querySelector('.iframe-box')
    
    player.value = new EZUIKit.EZUIKitPlayer({
        id: 'plackback' + props.options.onlyId, // 视频容器ID
        accessToken: props.options.accessToken,
        url,
        template: 'simple', // simple - 极简版;standard-标准版;security - 安防版(预览回放);voice-语音版; theme-可配置主题；
        // plugin: ['talk'],                       // 加载插件，talk-对讲
        width: element.offsetWidth,
        height: element.offsetHeight + 48 // 回放顶部有个标题，类名为header-controls，隐藏掉需要补充高度
    })
    setTimeout(() => {
        nextTick(() => {
            const el = document.querySelector(`#plackback${props.options.onlyId}-loading-item-0`)
            if (el && el.firstChild.innerText === '播放失败请重试') {
                el.firstChild.innerText = '同一时刻只能有一个用户查看回放，请确保没有其他用户同时查看回放'
            }
        })
    }, 5000)
    state.dialogVisible = false
}

defineExpose({
    resetMoni
    
})

</script>

<style lang="scss" scoped>
.monitor {
height: 100%;
width: 100%;
.monitor-head {
  height: 30px;
  padding: 0 10px;
  background: #3494dd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .menu-list {
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 30px;
      img {
          width: 16px;
          height: 16px;
          margin-left: 14px;
          vertical-align: middle;
      }
      .menu-btn {
          z-index: 99;
  cursor: pointer;
      }
  }
}
.iframe-box {
  height: calc(100% - 30px);
  position: relative;
  .iframe {
    height: 100%;
    width: 100%;
  }
  .mask-layer {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 99;
  }
  .direction {
    position: absolute;
    height: 100px;
    width: 100px;
    cursor: pointer;
    background: url("@/assets/monitor/direction.png");
    background-size: 100% 100%;
    z-index: 100;
  }
  .top {
    left: 50%;
    top: 0;
    transform: rotate(-90deg) translateY(-50%);
  }
  .left {
    top: 50%;
    left: 0;
    transform: rotate(180deg) translateY(50%);
  }
  .right {
    top: 50%;
    right: 0;
    transform: translateY(-50%);
  }
  .bottom {
    left: 50%;
    bottom: 0;
    transform: rotate(90deg) translateY(50%);
  }
}
.dialog-play-back {
  padding-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .time {
    margin-bottom: 10px;
  }
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.header-controls {
  display: none !important;
}
.footer-controls-right {
  .theme-icon-item:nth-child(2), .theme-icon-item:nth-child(3) {
    display: none;
  }
}
.timeline-controls-date {
  display: none;
}
.footer-controls {
  display: none !important;
}
.ez-iframe-footer-container {
  margin-top: 0 !important;
}
.timeline-controls {
  input {
    display: none !important;
  }
}
}
</style>